package com.sansecy.customview.view;

import android.content.Context;
import android.graphics.Canvas;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import android.util.AttributeSet;
import android.view.View;

import com.sansecy.customview.R;


public class IndicatorLayoutConstraintLayout extends ConstraintLayout {

    private int mMeasuredWidth;
    private int mMeasuredHeight;
//    private Paint mPaint;
    private float ratio;

    public IndicatorLayoutConstraintLayout(@NonNull Context context) {
        this(context, null);
    }

    public IndicatorLayoutConstraintLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setWillNotDraw(false);
//        mPaint = new Paint();

    }

    public void setDelta(float delta, float total) {
        ratio = delta / total;
        requestLayout();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mMeasuredWidth = getMeasuredWidth();
        mMeasuredHeight = getMeasuredHeight();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
//        canvas.drawLine(getMeasuredWidth() / 2f, 0, getMeasuredWidth() / 2f, getMeasuredHeight(), mPaint); //中线，测试用
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View widget = getChildAt(i);
            if (widget.getId() == R.id.indicator) {
                int itemWidth = mMeasuredWidth / 8;
                int canMoveWidth = mMeasuredWidth - itemWidth * 2;
                int center = mMeasuredWidth / 2;
                int measuredWidth = widget.getMeasuredWidth();

                int widgetCenterX = (int) (center + ratio * canMoveWidth / 2);
                int widgetLeft = widgetCenterX - measuredWidth / 2;
                int widgetRight = widgetCenterX + measuredWidth / 2;
                int widgetTop = (int) (mMeasuredHeight - widget.getMeasuredHeight() * 0.4);

                int widgetBottom = widgetTop + widget.getMeasuredHeight();
                widget.layout(widgetLeft, widgetTop, widgetRight, widgetBottom);
            }
        }
    }
}
